package com.relife.core.easyui;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.relife.common.model.Page;
import com.relife.common.utils.ReflectUtil;
import com.relife.common.utils.StringUtil;
import org.hibernate.collection.internal.PersistentBag;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


public class Easyui {
	/**
	 * 
	 * @author WU
	 * @date 2015-5-26 下午11:10:04
	 * @param p
	 * @param res
	 */
	@SuppressWarnings("unchecked")
	public static void datagrid(Page p, HttpServletResponse res) {
		JSONObject obj = new JSONObject();
		obj.put("total", p.getTotal());
		Object[] values = new Object[p.getField().length];
		JSONArray rows = new JSONArray();
		for (int j = 0; j < p.getList().size(); j++) {
			JSONObject o = new JSONObject();
			for (int i = 0; i < p.getField().length; i++) {
				String fieldName = p.getField()[i];
				if (p.getList().get(j) instanceof Map) {
					values[i] = ((Map<String, Object>) p.getList().get(j)).get(fieldName);
				} else {
					values[i] = getValue(p.getList().get(j), fieldName);
				}
				o.put(fieldName, values[i] == null ? "" : values[i]);
			}
			rows.add(o);
		}
		obj.put("rows", rows);
		write(res, obj);
	}

	@SuppressWarnings("unchecked")
	public static void ztree(Page p, HttpServletResponse res, boolean open) {
		Object[] values = new Object[p.getField().length];
		JSONArray rows = new JSONArray();
		for (int j = 0; j < p.getList().size(); j++) {
			JSONObject o = new JSONObject();
			for (int i = 0; i < p.getField().length; i++) {
				String fieldName = p.getField()[i];
				if (p.getList().get(j) instanceof Map) {
					values[i] = ((Map<String, Object>) p.getList().get(j)).get(fieldName);
				} else {
					values[i] = getValue(p.getList().get(j), fieldName);
				}
				o.put(fieldName, values[i] == null ? "" : values[i]);
			}
			if (open)
				o.put("open", open);
			rows.add(o);
		}
		write(res, rows);
	}

	/**
	 * 
	 * @author WU
	 * @date 2015-5-27 下午7:47:15
	 * @param p
	 * @param res
	 */
	public static void treegrid(Page p, HttpServletResponse res) {
		Object[] values = new Object[p.getField().length];
		JSONArray rows = new JSONArray();
		for (int j = 0; j < p.getList().size(); j++) {
			JSONObject o = new JSONObject();
			for (int i = 0; i < p.getField().length; i++) {
				String fieldName = p.getField()[i];
				values[i] = getValue(p.getList().get(j), fieldName);
				o.put(fieldName, values[i] == null ? "" : values[i]);
			}
			PersistentBag bag = (PersistentBag) getValue(p.getList().get(j), p.getChildren());
			if (bag != null && bag.size() > 0) {
				o.put("state", "closed");
			} else {
				o.put("state", "open");
			}
			rows.add(o);
		}
		write(res, rows);
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年4月3日 下午10:49:20
	 * @param p
	 * @param res
	 */
	public static void treegrAll(Page p, HttpServletResponse res) {
		Object[] values = new Object[p.getField().length];
		JSONArray rows = new JSONArray();
		for (int j = 0; j < p.getList().size(); j++) {
			JSONObject o = new JSONObject();
			for (int i = 0; i < p.getField().length; i++) {
				String fieldName = p.getField()[i];
				values[i] = getValue(p.getList().get(j), fieldName);
				o.put(fieldName, values[i] == null ? "" : values[i]);
			}
			PersistentBag bag = (PersistentBag) getValue(p.getList().get(j), p.getChildren());
			if (bag != null && bag.size() > 0) {
				JSONArray array = new JSONArray();
				for (int i = 0; i < bag.size(); i++) {
					array.add(entity2JSONObject(bag.get(i), (p.getFields() + ",children").split(",")));
				}
				o.put("children", array);
			}
			rows.add(o);
		}
		write(res, rows);
	}

	/**
	 * 
	 * @author WU
	 * @date 2015-5-26 下午11:09:51
	 * @param list
	 * @param tree
	 * @param res
	 */
	public static <T> void tree(List<T> list, Tree tree, HttpServletResponse res) {
		JSONArray array = new JSONArray();
		for (int j = 0; j < list.size(); j++) {
			JSONObject o = new JSONObject();
			o.put("id", getValue(list.get(j), tree.getId()));
			o.put("text", getValue(list.get(j), tree.getText()));
			PersistentBag bag = (PersistentBag) getValue(list.get(j), tree.getChildren());
			if (bag != null && bag.size() > 0) {
				o.put("state", "closed");
			} else {
				o.put("state", "open");
			}
			array.add(o);
		}
		write(res, array);
	}

	/**
	 * 
	 * @author WU
	 * @date 2014-10-30 下午8:50:22
	 * @param entity
	 * @param entityName
	 *            节点状态, 'open' 或者 'closed'
	 * @return
	 */
	public static <T> void treeAll(List<T> entity, String[] entityName, HttpServletResponse res) {
		JSONArray array = new JSONArray();
		for (int i = 0; i < entity.size(); i++) {
			array.add(entity2JSONObject(entity.get(i), entityName));
		}
		write(res, array);
	}

	/***
	 * 
	 * @author WU
	 * @date 2014-10-30 下午4:48:30
	 * @param entity
	 * @param entityName
	 * @return
	 */
	public static <T> JSONObject entity2JSONObject(T entity, String[] entityName) {
		JSONObject json = new JSONObject();
		for (int i = 0; i < entityName.length; i++) {
			String name, key;
			if (entityName[i].contains(":")) {
				String[] var = entityName[i].split(":");
				key = var[0];
				name = var[1];
			} else {
				name = entityName[i];
				key = entityName[i];
			}
			if (name.contains(".")) {

			} else {
				Object obj = getValue(entity, name);
				if (obj == null)
					continue;
				String type = obj.getClass().toString();
				if (type.contains("org.hibernate.collection.internal.PersistentBag")) {
					PersistentBag bag = (PersistentBag) obj;
					JSONArray list = new JSONArray();
					for (int j = 0; j < bag.size(); j++) {
						list.add(entity2JSONObject(bag.get(j), entityName));
					}
					json.put(key, list);
				} else {
					json.put(key, obj);
				}
			}
		}
		return json;
	}

	/**
	 * 根据属性名称获取对应的值
	 * 
	 * @author WU
	 * @date 2015-5-18 上午12:52:24
	 * @param entity
	 * @param fieldName
	 * @return
	 */
	public static <T> Object getValue(T entity, String fieldName) {
		Object value = ReflectUtil.getValue(entity, fieldName);
		if (value instanceof Timestamp) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
			value = sdf.format(value);
		} else if (value instanceof Date) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
			value = sdf.format(value);
		}
		return value;
	}

	/**
	 * 
	 * @author WU
	 * @date 2017年3月28日 下午5:20:47
	 * @param list
	 * @param keys
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> JSONArray List2JSONArray(List<T> list, String keys) {
		JSONArray array = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i) instanceof Map) {
				String[] key = keys.split(",");
				JSONObject obj = new JSONObject();
				for (int j = 0; j < key.length; j++) {
					if (key[j].contains(":")) {
						String[] var = key[j].split(":");
						obj.put(var[1], ((Map<String, Object>) list.get(i)).get(var[0]));
					} else {
						obj.put(key[j], ((Map<String, Object>) list.get(i)).get(key[j]));
					}
				}
				array.add(obj);
			} else {
				array.add(bean2JSONObject(list.get(i), keys));
			}
		}
		return array;
	}

	/**
	 * 
	 * @author WU
	 * @date 2017年3月28日 下午5:20:40
	 * @param entity
	 * @param keys
	 * @return
	 */
	public static <T> JSONObject bean2JSONObject(T entity, String keys) {
		JSONObject obj = new JSONObject();
		if (StringUtil.isNotEmpty(keys)) {
			String[] key = keys.split(",");
			for (int j = 0; j < key.length; j++) {
				obj.put(key[j], getValue(entity, key[j]));
			}
		}
		return obj;
	}

	/**
	 * 写出消息到页
	 * 
	 * @author WU
	 * @date 2016年6月29日 下午2:20:02
	 * @param res
	 * @param obj
	 */
	public static void write(HttpServletResponse res, Object obj) {
		try {
			res.setContentType("text/html;charset=utf-8");
			res.getWriter().println(obj);
			res.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
